//
// Created on 2025/4/14.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
// please include "napi/native_api.h".
#include <multimedia/player_framework/native_avcodec_base.h>
#include <multimedia/player_framework/native_avcodec_videoencoder.h>
#ifndef SAMPLE_ENCODER_NAPI_H
#define SAMPLE_ENCODER_NAPI_H
#include "common.h"
#include <mutex>
#include <queue>
#include <fstream>

struct  CodecBufferInfo {
    CodecBufferInfo(uint32_t index, OH_AVBuffer *buffer): index(index), buffer(buffer), isValid(true) {}
    CodecBufferInfo(uint32_t index, OH_AVFormat *parameter): index(index), parameter(parameter), isValid(true) {}
    OH_AVBuffer *buffer = nullptr;
    OH_AVFormat *parameter = nullptr;
    uint32_t index = 0;
    bool isValid = true;
};


class VideoEncoder {
public:
    VideoEncoder() ;
    ~VideoEncoder();
    static void OnError(OH_AVCodec *codec, int32_t errorCode, void *userData);
    static void OnStreamChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData);
    static void OnNeedInputBuffer(OH_AVCodec *codec, uint32_t index, OH_AVBuffer *buffer, void *userData);
    static void OnNewOutputBuffer(OH_AVCodec *codec, uint32_t index, OH_AVBuffer *buffer, void *userData);
    static std::mutex inQueueMutex;
    static std::mutex outQueueMutex;

    static std::queue<CodecBufferInfo> inQueue;
    static std::queue<CodecBufferInfo> outQueue;
    
    int32_t widthStride;
    std::unique_ptr<std::ifstream> inputFile;
    std::unique_ptr<std::ofstream> outputFile;
    
    void EncodeInt(SampleInfo sampleInfo);
    void InputThread();
    void OutputThread();
    //void WidthOffset(buffer, bufferInfo.buffer));
    //WidthOffset(buffer, bufferInfo.buffer);
private:
    SampleInfo sampleInfo_;  
    OH_AVCodec* encoder = nullptr;
    std::mutex encoderMutex;
    std::unique_ptr<std::thread> inthread;
    std::unique_ptr<std::thread> outthread;
    
};

// void OnError(OH_AVCodec *codec, int32_t errorCode, void *userData);
// void OnStreamChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData);
// void OnNeedInputBuffer(OH_AVCodec *codec, uint32_t index, OH_AVBuffer *buffer, void *userData);
// void OnNewOutputBuffer(OH_AVCodec *codec, uint32_t index, OH_AVBuffer *buffer, void *userData);


#endif //SAMPLE_ENCODER_NAPI_H
